package gewu.suleju.controller;

import gewu.suleju.dao.iml.IUserDao;
import gewu.suleju.model.pojo.User;
import gewu.suleju.model.vo.PhoneCode;
import gewu.suleju.model.vo.Result;
import gewu.suleju.rbm.RbmConst;
import gewu.suleju.sevice.imp.UserServiceImp;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping("userRegister")//注册
public class UserRegisterController {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserServiceImp userServiceImp;
    @Autowired
    private IUserDao iUserDao;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @PostMapping("checkCode")
    @ResponseBody
    public Result checkCode(String phone){
        if(phone == null){//判断是否为空
            return new Result("500","请输入电话号码");
        }
        User user = userServiceImp.findUserByPhone(phone);
        String checkphone = String.valueOf((int) (Math.random() * 900000 + 100000));

        PhoneCode phoneCode = new PhoneCode(phone,checkphone);
        rabbitTemplate.convertAndSend(RbmConst.SIMPLE_QUEUE01,phoneCode);//传入消费者名

        redisTemplate.opsForValue().set(phone,checkphone,60, TimeUnit.SECONDS);
        return new Result("200","发送成功！",phoneCode);
    }
    @ResponseBody
    @PostMapping("save")
    public Result save(String inputPhone,String inputPassword,String checkCode){
        String checkCode1 = (String) redisTemplate.opsForValue().get(inputPhone);
        if(!checkCode.equals(checkCode1)){
            return new Result("500","验证码已经过期！");
        }
        User user = userServiceImp.findUserByPhone(inputPhone);
        if(user != null){
            return new Result("501","你已经注册过了,请登录");
        }
        User user1 = new User();
        user1.setUsername(inputPhone);
        user1.setPassword(inputPassword);
        user1.setPhone(inputPhone);
        iUserDao.save(user1);//数据库里新增数据

        return new Result("200","注册成功！");
    }
}
